package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"fmt"
	"time"

	log "github.com/sirupsen/logrus"
)

// 获取Boss礼包
func GetBossPack(u *m.User) (bp *m.BossPack, err error) {
	bp = m.GetBossPack(u.Uid.Hex())

	lst := make([]int64, 0)
	now := utils.TNow().Unix()
	for key, val := range bp.MGiftPack { // 检查超时的礼包
		if now > val.EndTime {
			lst = append(lst, key)
		}
	}
	// 删除超时的礼包
	for _, item := range lst {
		delete(bp.MGiftPack, item)
	}
	bp.Update(bp)
	return
}

// 购买Boss礼包
func BuyBossPack(from string, u *m.User, packId int64, PSend func(interface{}) error) (buyingPackId int64, bp *m.BossPack, uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, err error) {
	bp = m.GetBossPack(u.Uid.Hex())
	defer bp.Update(bp)

	monsterID := int64(0)
	for key, val := range bp.MGiftPack {
		if val.PackId == packId {
			monsterID = key
			break
		}
	}
	if monsterID == 0 {
		err = errors.NewErrcode(data.Errcode.NotFound, fmt.Sprintf("玩家没有该boss礼包 %d", packId))
		return
	}

	tpl, ok := data.Get("PaidPropsPacks", uint64(packId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表PaidPropsPacks")
		return
	}
	tplT := tpl.(data.PaidPropsPack)
	// 打包道具
	giveGoods := make([]m.BaseKV, 0)
	for _, item := range tplT.Goods {
		gtpl, ok := data.Get("Goods", item.Key)
		if !ok {
			err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表Goods")
			return
		}
		gtplT := gtpl.(data.Good)
		if int64(gtplT.Category) == data.GoodsCategoryEnum.CategoryLv3 { // 宝箱，需要一个一个给
			for i := int64(0); i < int64(item.Value); i++ {
				giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: 1})
			}
		} else {
			giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: int64(item.Value)})
		}
	}
	// 给用户道具
	uProp, resGoods, boxResList, err = GiveGoodsByKvList(from, u, giveGoods, PSend)
	if err != nil {
		return
	}

	delete(bp.MGiftPack, monsterID)
	buyingPackId = packId
	return
}

// 重置Boss礼包
func ResetBossPack(u *m.User) {
	bp := m.GetBossPack(u.Uid.Hex())
	bp.MGiftPack = make(map[int64]*m.BossPackInfo)
	bp.Update(bp)
}

// 击杀boss，添加Boss礼包
func DoneBossPack(u *m.User, monsterID int64) {
	bp := m.GetBossPack(u.Uid.Hex())

	tpl, ok := data.Get("BossPaidPacks", uint64(monsterID))
	if !ok {
		log.WithFields(log.Fields{
			"uid":       u.Uid.Hex(),
			"method":    "DoneBossPack",
			"monsterID": monsterID,
		}).Error("没有BossPaidPacks配表")
		return
	}
	tplT := tpl.(data.BossPaidPack)
	lst := tplT.Lst[0]
	beginTime := utils.TNow().Unix()
	endTime := utils.TNow().Add(time.Hour * time.Duration(lst.Value)).Unix()
	bp.MGiftPack[monsterID] = &m.BossPackInfo{
		MonsterID: monsterID,
		PackId:    int64(lst.Key),
		BeginTime: beginTime,
		EndTime:   endTime,
	}

	bp.Update(bp)
	return
}
